<?php
namespace App\Http\Controllers;
use App\Activity;
use App\Business;
use Illuminate\Http\Request;

trait Search {

	public function getSearchWhere(Request $request) {
		$mapIds = $this->getSearchMapIds($request);
		if (empty($mapIds)) {
			return "0 = 1";
		}
		$where = ' map_id in (' . implode(',', $mapIds) . ')';
		$this->getInputValue($request, $where);
		$this->getTime($request, $where);
		return $where;
	}

	public function getBusiness($effective = false) {
		$user = session('user');
		$business = $user->is_admin ? (new Business)->all() : $user->business;
		$business->load(['activitys' => function ($query) use ($effective) {
			$where = $effective ? 'status = 1 and IF(start=0, 1=1, start_time > DATE_ADD(NOW(), INTERVAL - days DAY))' : '1 = 1';
			return $query->whereRaw($where)->groupBy('activity_id', 'business_id')->orderBy('created_at', 'asc');
		}]);
		return $business;
	}

	public function getSearchMapIds(Request $request) {
		$allMapIds = $this->getBasicMapId();
		$whereMapIds = $this->getMapId($request);
		return $whereMapIds ? array_merge(array_unique(array_intersect($allMapIds, $whereMapIds))) : $allMapIds;
	}

	private function getInputValue(Request $request, &$where) {
		$searchKey = $request->input('searchKey');
		$searchValue = $request->input('searchValue');
		if ($searchKey && $searchValue) {
			$where .= ' and ' . $searchKey . " like '%" . $searchValue . "%'";
		}
	}

	private function getTime(Request $request, &$where) {
		$startTime = $request->input('start_time');
		$endTime = $request->input('end_time');
		if ($startTime && $endTime) {
			$where .= ' and created_at between "' . $startTime . '" and "' . $endTime . '"';
		} else if ($startTime) {
			$where .= ' and created_at > "' . $startTime . '"';
		} else if ($endTime) {
			$where .= ' and created_at < "' . $startTime . '"';
		}
	}

	private function getBasicMapId() {
		$user = session('user');
		if ($user->is_admin) {
			$business = (new Business)->with('maps')->get();
		} else {
			$business = $user->business->load('maps');
		}
		if (!count($business)) {
			return [];
		}
		$maps = $map_ids = [];
		foreach ($business as $key => $value) {
			array_push($maps, $value->maps->toArray());
		}
		if (empty($maps)) {
			abort(404);
		}
		foreach ($maps as $key => $value) {
			if (is_array($value)) {
				$ids = array_column($value, 'id');
				$map_ids = array_merge($map_ids, $ids);
			}
		}
		return $map_ids;
	}

	private function getMapId(Request $request) {
		$map_id = $request->input('map');
		if ($map_id) {
			return (array) $map_id;
		}
		$activity_id = $request->input('activity');
		$business_id = $request->input('business');
		if ($activity_id) {
			$maps = (new Activity)->findOrFail($activity_id)->maps()->where('business_id', $business_id)->get();
			return array_column($maps->toArray(), 'id');
		}
		if ($business_id) {
			$maps = (new Business)->findOrFail($business_id)->maps;
			return array_column($maps->toArray(), 'id');
		}
		return [];
	}
}